package com.foreveross.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.foreveross.common.Constants;
import com.foreveross.dao.HrNewsInfoDAO;
import com.foreveross.dao.NewsHouseDAO;
import com.foreveross.vo.HrHouses;
import com.foreveross.vo.HrNewsInfo;
import com.foreveross.vo.NewsHouse;

@Service("newsHouseService")
@Transactional
public class NewsHouseService extends BaseService {

	@Resource
	HrNewsInfoDAO newsInfoDAO;
	
	@Resource
	NewsHouseDAO newsHouseDAO;
	
	/**
	 * 管理员发布资讯
	 * @param message
	 * @param houseIds
	 * @throws Exception
	 */
	public void addHrNewsInfo(HrNewsInfo hrNewsInfo,String houseIds) throws Exception{
		if(null != hrNewsInfo.getId() && !"".equals(hrNewsInfo.getId())){
			boundNews(hrNewsInfo, houseIds);
		}else{
			hrNewsInfo.setIsAll(Constants.IS_ALL);
			hrNewsInfo.setCreateTime(new Date());
			newsInfoDAO.save(hrNewsInfo);
			if(null != houseIds && !"".equals(houseIds)){
				hrNewsInfo.setIsAll(Constants.NOT_ALL);
				newsInfoDAO.updateObject(hrNewsInfo);
				for(String houseId : houseIds.split(",")){
					HrHouses house = new HrHouses(houseId);
					
					NewsHouse messageHouse = new NewsHouse(house, hrNewsInfo);
					newsHouseDAO.save(messageHouse);
				}
			}
		}
	}
	
	/**
	 * 资讯绑定楼盘
	 * @param favorableId
	 * @param houseIds
	 */
	private void boundNews(HrNewsInfo newsInfo,String houseIds) throws Exception{
		String newsId = newsInfo.getId();
		deleteNewsHouseByNewsId(newsId);
		if(null != houseIds && !"".equals(houseIds)){
			newsInfo.setIsAll(Constants.NOT_ALL);
			newsInfoDAO.updateObject(newsInfo);
			for(String houseId : houseIds.split(",")){
				HrHouses house = new HrHouses(houseId);
				if(getNewsHouseListCount(newsId, houseId)==0){
					NewsHouse newsHouse = new NewsHouse(house, newsInfo);
					newsHouseDAO.save(newsHouse);
				}
			}
		}else{
			newsInfo.setIsAll(Constants.IS_ALL);
			newsInfoDAO.updateObject(newsInfo);
		}
	}
	
	public long getNewsHouseListCount(String newsId,String houseId)
			throws Exception{
		return newsHouseDAO.findNewsHouseListCount(newsId, houseId);
	}
	
	public List<NewsHouse> getNewsHouseList(String newsId,String houseId,
			int pageIndex,int pageSize) throws Exception{
		return newsHouseDAO.findNewsHouseList(newsId, houseId, pageIndex, pageSize);
	}
	
	public void deleteNewsHouse(String ids) throws Exception{
		if(ids == null) return ;
		for(String id :ids.split(",")){
			newsHouseDAO.deleteNewsHouse(id);
		}
	}
	
	private void deleteNewsHouseByNewsId(String newsId) throws Exception{
		newsHouseDAO.deleteNewsHouseByNewsId(newsId);
	}
}
